package com.orange.cetback.controller.user;

import com.orange.cetback.common.utils.SiliconFlowUtil;
import com.orange.cetback.common.vo.Result;
import com.orange.cetback.pojo.dto.SiliconChatDTO;
import com.orange.cetback.pojo.vo.ChatVO;
import com.orange.cetback.pojo.vo.SiliconChatResponse;
import com.orange.cetback.service.SiliconFlowService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import reactor.core.publisher.Flux;
import reactor.core.scheduler.Schedulers;

import java.util.concurrent.Executor;

@Slf4j
@Tag(name = "智能对话接口")
@RestController
@RequestMapping("/userApi/silicon")
@RequiredArgsConstructor
public class SiliconFlowController {

    @Autowired
    private SiliconFlowUtil siliconFlowUtil;

    @Autowired
    private SiliconFlowService siliconFlowService;
    @Operation(summary = "文本对话")
    @PostMapping("/chat")
    public Result<ChatVO> chat(@RequestBody @Valid SiliconChatDTO dto) {
        log.info("chat:{}", dto);
        ChatVO chatVO = siliconFlowService.handleChatRequest(dto);

        return Result.success(chatVO);
    }

    @Operation(summary = "流式对话")
    @PostMapping(value = "/streamChat", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public SseEmitter streamChat(@RequestBody @Valid SiliconChatDTO dto) {
        log.info("streamChat:{}", dto);
        SseEmitter emitter = new SseEmitter(60 * 1000L); // 超时60秒
        siliconFlowUtil.streamChatCompletion(dto, emitter);
        return emitter;
    }

    @GetMapping(value = "/stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
    public Flux<String> streamToFrontend() {
        return siliconFlowService.streamFromThirdParty()
                .map(data -> {
                    // 可选：处理或转换数据格式
                    return "data: " + data + "\n\n"; // SSE格式要求
                });
    }



}
